package cn.itsource.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpUtil;
import cn.itsource.basic.domain.*;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.BinderDTO;
import cn.itsource.org.domain.User;
import cn.itsource.org.domain.WxUser;
import cn.itsource.org.mapper.UserMapper;
import cn.itsource.org.mapper.WxUserMapper;
import cn.itsource.org.service.WechartService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Objects;

@Service
public class WechartServiceImpl implements WechartService {
    @Autowired
    WechartProperties wechartProperties;
    @Autowired
    WxUserMapper wxUserMapper;
    @Autowired
    RedisService redisService;
    @Autowired
    UserMapper userMapper;

    //这里进入到回调接口
    @Override
    public String callback(String code) {
        //1.完成用户授权的操作,得到用户的token信息
        //这里得到的是一个获取token的url
        /**------------------ 第二步:通过授权码获取用户的token ---------------*/
        String getTokenUrl = String.format(wechartProperties.getTokenUrl(), wechartProperties.getAppId(), wechartProperties.getAppSecrect(), code);
        //现在需要向微信三方服务器发送获取用户token的请求
        String tokenJson = HttpUtil.get(getTokenUrl);
        //需要将得到的json字符串转换成我们的java对象
        WechartTokenDto tokenDto = JSON.parseObject(tokenJson, WechartTokenDto.class);
        /**------------------ 第三步步:通过token获取用户的资源信息 ---------------*/
        String getResourceURl = String.format(wechartProperties.getUserinfoUrl(),tokenDto.getAccess_token(),tokenDto.getOpenid() );
        //现在需要向微信三方服务器发送获取用户token的请求
        String resourceJson = HttpUtil.get(getResourceURl);
        WechartUserInfoDto userInfoDto = JSON.parseObject(resourceJson, WechartUserInfoDto.class);
        System.out.println("最终用户信息:"+userInfoDto);

        //通过用户的openid查询
        WxUser wxUser = wxUserMapper.findByOpenId(userInfoDto.getOpenid());
        if (Objects.nonNull(wxUser)) {
            //1.1存在,判断userId
            if (Objects.isNull(wxUser.getUserId())){
                //跳转绑定页面
                return "redirect:http://127.0.0.1:8082/binder.html?openId="+userInfoDto.getOpenid();
            }else {
                //跳转到首页
                String uuid = IdUtil.fastSimpleUUID();
                User user = userMapper.selectByPrimaryKey(wxUser.getUserId());
                UserInfo userInfo = BeanUtil.copyProperties(user, UserInfo.class);
                redisService.setStringKeyAndValue(uuid,userInfo,30L);
//                return "redirect:http://127.0.0.1:8082/index.html?openId="+userInfoDto.getOpenid();
                return "redirect:http://127.0.0.1:8082/index.html?token="+uuid+"&username="+user.getUsername()+"&phone="+user.getPhone();
            }
        }
        //不存在,首先先将数据存入t_wxuser表,然后跳转到绑定页面
        WxUser wxUser1 = BeanUtil.copyProperties(userInfoDto, WxUser.class);
        wxUserMapper.insertSelective(wxUser1);
        //跳转到绑定页面
        return "redirect:http://127.0.0.1:8082/binder.html?openId="+userInfoDto.getOpenid();
    }

    @Override
    public AjaxResult binder(BinderDTO binderDTO) {
        //判断验证码是否一致
        //判断手机号是否存在
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("phone", binderDTO.getPhone());
        User user = userMapper.selectOneByExample(example);
        //手机号不存在
        if(Objects.isNull(user)){
            //手机号不存在
            //将手机号添加到user表中
            User user1 = BeanUtil.copyProperties(binderDTO, User.class);
            //设置密码
            user1.setPassword("123456");
            //密码加密
            String password = user1.getPassword();
            String salt = RandomUtil.randomString(6);
            String s = MD5.create().setSalt(salt.getBytes()).digestHex(password);
            user1.setUsername(user1.getPhone());
            user1.setSalt(salt);
            user1.setPassword(s);
            userMapper.insertSelective(user1);
            //根据openid查询到对应的wxuser
            WxUser wxUser = wxUserMapper.findByOpenId(binderDTO.getOpenId());
            //将对应的userid写入
            wxUser.setUserId(user1.getId());
            wxUserMapper.updateByPrimaryKeySelective(wxUser);
            String uuid = IdUtil.fastSimpleUUID();
            UserInfo userInfo = BeanUtil.copyProperties(user1, UserInfo.class);
            redisService.setStringKeyAndValue(uuid, userInfo, 30);
            LoginVO loginVO = new LoginVO(uuid, userInfo);
            return AjaxResult.setResult(loginVO);
        }else{//有手机号
            WxUser wxUser = wxUserMapper.findByOpenId(binderDTO.getOpenId());
            if(Objects.isNull(wxUser.getUserId())){
                //1.没有绑定微信
                wxUser.setUserId(user.getId());
                wxUserMapper.updateByPrimaryKeySelective(wxUser);
                String uuid = IdUtil.fastSimpleUUID();
                UserInfo userInfo = BeanUtil.copyProperties(user, UserInfo.class);
                redisService.setStringKeyAndValue(uuid, userInfo, 30);
                LoginVO loginVO = new LoginVO(uuid, userInfo);
                return AjaxResult.setResult(loginVO);
            }else{
                return AjaxResult.me();
            }
        }

    }

    @Override
    public AjaxResult exist(String phone) {
        String s = "[1][3,4,5,7,8][0-9]{8}";

        if(phone.matches(s)){
            return AjaxResult.setMsg("请输出正确的手机号");
        }
        return AjaxResult.me();
    }
}
